package com.yqg.education.utils;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

//存入将监控数据txt文件
@Component
@Slf4j
public class DataSaver {
    @Value("${data.upload.path}")
    private String storageDir;
    private static final String DATE_PATTERN = "yyyy-MM-dd";
    private static final String TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";


    private final SimpleDateFormat dateSdf = new SimpleDateFormat(DATE_PATTERN);
    private final SimpleDateFormat timeSdf = new SimpleDateFormat(TIME_PATTERN);


    @Autowired
    private TaskExecutor dataSavingThreadPool;// 注入自定义线程池

    @Async("dataSavingThreadPool")
    public void saveDataToFileAsync(String data, String sendTime, String src) {
        saveDataToFile(data, sendTime, src);
    }

    public void saveDataToFile(String data, String sendTime, String src) {
        if (ObjectUtil.isNotEmpty(data)) {
            try {
                String currentDate = dateSdf.format(new Date());
                String filePath = storageDir + "/" + currentDate + ".txt";
                StringBuilder contentBuilder = new StringBuilder();
                contentBuilder.append(sendTime).append(": ").append(src).append(": ").append(data);
                try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true))) {
                    bw.newLine(); // 新建一行
                    bw.write(contentBuilder.toString()); // 写入内容
                    bw.newLine(); // 再新建一行以便区分不同数据块
                    bw.flush();
                    log.info("【{}】：已成功将数据写入到TXT文件: {}", new Date(), filePath);
                } catch (IOException e) {
                    log.error("保存数据到文件时发生错误", e);
                }
            } catch (Exception e) {
                log.error("处理数据时发生错误", e);
            }
        } else {
            log.info("接收数据为空，不做文件写入操作！");
        }
    }
}
